//
// Created by xzy.xiao on 2022/6/10.
//

#include "EventLabel.h"
#include <QMouseEvent>
#include <QMessageBox>

/**
 * 分发各种事件
 * @param e 事件
 * @return true：事件已被识别并被处理
 */
bool EventLabel::event(QEvent *e) {
    if (myKeyEvent(e)) {
        return true;
    }

    return QLabel::event(e);
}

/**
 * 处理鼠标移动事件
 * @param ev -
 */
void EventLabel::mouseMoveEvent(QMouseEvent *ev) {
    const QString &msg = QString::asprintf("<center><h1> mouse move：(%d,%d) </h1></center>", ev->x(), ev->y());
    this->setText(msg);

    QLabel::mouseMoveEvent(ev);
}

/**
 * 处理鼠标点击事件
 * @param ev -
 */
void EventLabel::mousePressEvent(QMouseEvent *ev) {
    const QString &msg = QString::asprintf("<center><h1> mouse press：(%d,%d) </h1></center>", ev->x(), ev->y());
    this->setText(msg);

    QLabel::mousePressEvent(ev);
}

/**
 * 处理鼠标释放事件
 * @param ev -
 */
void EventLabel::mouseReleaseEvent(QMouseEvent *ev) {
    const QString &msg = QString::asprintf("<center><h1> mouse release：(%d,%d) </h1></center>", ev->x(), ev->y());
    this->setText(msg);

    QLabel::mouseReleaseEvent(ev);
}

/**
 * 窗口关闭事件
 * @param event -
 */
void EventLabel::closeEvent(QCloseEvent *event) {
    if (ifContinueToClose()) {
        event->accept();
    } else {
        event->ignore();
    }
}

/**
 * 自定义的事件：键盘 K 键被按下
 * @param e -
 * @return true：事件已被识别并被处理
 */
bool EventLabel::myKeyEvent(QEvent *e) {
    if (QEvent::KeyPress == e->type()) {
        QKeyEvent *keyEvent = (QKeyEvent *) e;
        if (Qt::Key_K == keyEvent->key()) {
            QMessageBox::information(this, "My key Event", "K key is pressed");
            return true;
        }
    }

    return false;
}

// ==================== SUPPORT ====================

bool EventLabel::ifContinueToClose() {
    int choose = QMessageBox::question(
            this,
            "Quid",
            "Are you sure to quit this application ?",
            QMessageBox::Yes | QMessageBox::No,
            QMessageBox::No
    );

    return choose == QMessageBox::Yes;
}
